package com.bawei.lib_common.websocket

import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import com.bawei.lib_common.base.BaseApplication
import com.bawei.lib_common.base.utils.LoggerUtils
import com.google.gson.Gson
import com.tencent.liteav.base.ThreadUtils.runOnUiThread
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import java.util.Timer
import java.util.TimerTask

class WebSocketManager(
    val onMessage: (String) -> Unit,
    private val heartbeatInterval: Long = 30000, // 心跳间隔（默认30秒）
    private val heartbeatMessage: String = "ping" // 心跳消息内容（与服务端约定）
) {
    private val client = OkHttpClient()
    private var webSocket: WebSocket? = null
    private var reconnectAttempts = 0
    private val maxReconnectAttempts = 5
    private var isManualClose = false

    // 心跳相关变量
    private var heartbeatTimer: Timer? = null // 定时发送心跳的计时器
    private var isHeartbeatActive = false // 心跳是否激活（避免重复启动）
    private var lastPongTime: Long = 0 // 最后一次收到pong的时间（用于检测超时）

    companion object {
        // 心跳超时阈值（超过此时间未收到pong，认为连接断开）
        const val HEARTBEAT_TIMEOUT = 60000L // 60秒
    }

    // 启动WebSocket连接
    fun connect(url: String) {
        isManualClose = false
        // 先关闭旧连接
        webSocket?.close(1000, "Reconnect")
        val request = Request.Builder().url(url).build()
        webSocket = client.newWebSocket(request, object : WebSocketListener() {
            override fun onOpen(webSocket: WebSocket, response: Response) {
                // 连接成功后启动心跳
                startHeartbeat()
                reconnectAttempts = 0
                Log.d("WebSocket", "连接成功")
            }

            override fun onMessage(webSocket: WebSocket, text: String) {
                Log.d("WebSocket", "Received text: $text")
                if (text.contains("connect success")) return
                onMessage(text)
            }

            override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
                Log.d("WebSocket", "Received bytes: ${bytes.hex()}")
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                Log.d("WebSocket", "连接关闭: $reason")
                if (!isManualClose) tryReconnect(url)
                checkHeartbeatTimeout()
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                Log.e("WebSocket", "Error: ${t.message}")
                if (!isManualClose) tryReconnect(url)
                stopHeartbeat()
            }
        })
    }

    // 尝试重连
    fun tryReconnect(url: String) {
        if (reconnectAttempts < maxReconnectAttempts) {
            reconnectAttempts++
            connect( url)
        } else {
            Log.e("WebSocket", "重连次数过多，已停止重连")
        }
    }
    // 关闭连接
    fun disconnect() {
        isManualClose = true
        webSocket?.close(1000, "User disconnect")
        webSocket = null
        stopHeartbeat()
    }
    // 启动心跳（连接成功后调用）
    private fun startHeartbeat() {
        if (isHeartbeatActive) return // 避免重复启动

        isHeartbeatActive = true
        lastPongTime = System.currentTimeMillis() // 重置最后pong时间

        heartbeatTimer?.cancel() // 取消旧的计时器（如果有）
        heartbeatTimer = Timer().apply {
            scheduleAtFixedRate(object : TimerTask() {
                override fun run() {
                    // 心跳任务在后台线程执行，需切回主线程发送消息（OkHttp的send是线程安全的，但UI操作需注意）
                    runOnUiThread {
                        sendHeartbeat()
                    }
                }
            }, 0, heartbeatInterval) // 立即执行第一次心跳，之后每隔interval秒执行
        }
    }

    // 停止心跳（连接关闭或销毁时调用）
    private fun stopHeartbeat() {
        isHeartbeatActive = false
        heartbeatTimer?.cancel()
        heartbeatTimer = null
    }

    // 发送心跳消息
    private fun sendHeartbeat() {
        if (webSocket?.send(heartbeatMessage) == true) {
            // 心跳发送成功，记录时间（可选）
        } else {
            // 心跳发送失败（连接可能已断开），触发重连
            runOnUiThread {
                Toast.makeText(BaseApplication.instance, "心跳发送失败，尝试重连...", Toast.LENGTH_SHORT).show()
                webSocket?.close(1001, "Heartbeat failed") // 主动关闭连接（非正常关闭码）
            }
        }
    }
    // 在 WebSocketClient 中添加超时检测方法（可在 onClosed 或定时任务中调用）
    private fun checkHeartbeatTimeout() {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastPongTime > HEARTBEAT_TIMEOUT) {
            Log.e("WebSocket", "心跳超时，连接已断开")
            // 触发重连
//            scheduleReconnect()
        }
    }
}